package com.googlecode.milib.display {
	import com.googlecode.milib.actionControll.MLActionIniMidEnd;
	import com.googlecode.milib.display.MCAnimIniMidEnd;

	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.events.Event;

	/**
	 * @author Marek Brun
	 */
	public class MCAnimIniMidEndWithRemove extends MCAnimIniMidEnd {

		private var mc_parent:DisplayObjectContainer;
		private var isKeepIndex:Boolean;
		private var index:int;

		public function MCAnimIniMidEndWithRemove(mc:MovieClip, iniFrameStart:*=null, iniFrameEnd:*=null, endFrameStart:*=null, endFrameEnd:*=null, parent:MLActionIniMidEnd=null, midFrame:*=null, keepIndex:Boolean=false) {
			mc_parent=mc.parent;
			isKeepIndex=keepIndex;
			super(mc, iniFrameStart, iniFrameEnd, endFrameStart, endFrameEnd, parent, midFrame);
			mc.gotoAndStop('ini');
			if(!mc_parent){
				mc.addEventListener(Event.ADDED, onMCAdded, false, 0, true);
				isKeepIndex=false;
			}else{
				index=mc.parent.getChildIndex(mc);
				mc_parent.removeChild(mc);
			}
			
		}
		
		override protected function doStart():Boolean {
			if(super.doStart()){
				if(mc_parent){
					if(isKeepIndex){
						mc_parent.addChildAt(mc, index);					}else{
						mc_parent.addChild(mc);
					}
				}
				return true;
			}
			return false;
		}
		
		override protected function doFinish():Boolean {
			if(super.doFinish()){
				if(mc_parent){
					mc_parent.removeChild(mc);
				}
				return true;
			}
			return false;
		}

//********************************************************************************************
//		events for MCAnimIniMidEndWithRemove
//********************************************************************************************
		protected function onMCAdded(event:Event):void {
			dbg.log('onMCAdded '+dbg.link(mc));
			mc.removeEventListener(Event.ADDED, onMCAdded);
			mc_parent=mc.parent;
			if(!getIsRunning()){
				//mc_parent.removeChild(mc);
			}
		}
		
	}
}
